package com.kplan.admin.model.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import com.kplan.join.model.MemberDto;
import com.kplan.util.db.DBClose;
import com.kplan.util.db.DBConnection;

public class AdminDao {
	
	private static AdminDao dao;
	
	static {
		dao = new AdminDao();
	}
	
	private AdminDao(){}
	
	public static AdminDao getInstance() {
		return dao;
	}
	
	public int register(MemberDto memberDto) {
		int cnt = 0;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = DBConnection.makeConnection();
			String sql = "insert into member (email, nick, name, pass, age, gender, tel1, tel2, tel3, visited, togo, point, psum, status, bcode, max_planner) \n";
			sql += "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, 1, 0, 1)";
			pstmt = conn.prepareStatement(sql);
			int idx = 0;
			pstmt.setString(++idx, memberDto.getEmail());
			pstmt.setString(++idx, memberDto.getNick());
			pstmt.setString(++idx, memberDto.getName());
			pstmt.setString(++idx, memberDto.getPass());
			pstmt.setInt(++idx, memberDto.getAge());
			pstmt.setInt(++idx, memberDto.getGender());
			pstmt.setString(++idx, memberDto.getTel1());
			pstmt.setString(++idx, memberDto.getTel2());
			pstmt.setString(++idx, memberDto.getTel3());
			pstmt.setString(++idx, memberDto.getVisited());
			pstmt.setString(++idx, memberDto.getTogo());
			
			cnt = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBClose.close(conn, pstmt);
		}
		return cnt;
	}
	
	public List<MemberDto> findMember(String[] keyword) {
		List<MemberDto> list = new ArrayList<MemberDto>();
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBConnection.makeConnection();
			String sql = "select email, nick, name, status_name \n";
			sql += "from member m, status s \n";
			sql += "where m.status=s.status \n";
			sql += " and " + keyword[0] + " = '" + keyword[1] + "'";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				MemberDto memberDto = new MemberDto();
				memberDto.setEmail(rs.getString("email"));
				memberDto.setNick(rs.getString("nick"));
				memberDto.setName(rs.getString("name"));
				memberDto.setStatus_name(rs.getString("status_name"));
				list.add(memberDto);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBClose.close(conn, pstmt);
		}
		return list;
	}
}
